<?php

use console\db\Migration;
use yii\db\Query;
use yii\helpers\Console;

/**
 * 圈子回复信息缓存表转移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000007_t_sns_dynamic_comment extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%sns_dynamic_comment}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $db = Yii::$app->olddb;
        $options = $this->getTableOptions();
        $query = (new Query())->from('{{%' . $options['source'] . '}}');
        $count = $query->count('*', $db);
        $pagesize = 10000;
        $pages = ceil($count / $pagesize);
        $query->limit($pagesize);
        Console::startProgress(1, $pages, 'Updating objects: ', true);
        for ($i = 0; $i < $pages; $i++) {
            $this->handleProgress($query->offset($i * $pagesize), [$this, 'evenDule'], $options['columns'], $db);
            Console::updateProgress($i + 1, $pages);
        }
        Console::endProgress("update done.");
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->truncateTable($this->tableName);
    }

    /**
     * @inheritdoc
     */
    public function filterData(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        if ($data['gid'] != 1) {
            return false;
        }
        $username = str_ireplace(['INSERT INTO', 'script'], '', $data['uname']);
        if ($username !== $data['uname']) {
            return false;
        }
        $message = str_ireplace(['INSERT INTO', 'script'], '', $data['message']);
        if ($message !== $data['message']) {
            return false;
        }
        $message = trim(strip_tags($message));
        if (!$message) {
            return false;
        }
        $data['listener'] = '';
        $pattern = '/回复[\s]([\s\S]*?)[\s|:]+(.*)/i';
        preg_match($pattern, $message, $matchs);
        if (!empty($matchs)) {
            $message = trim($matchs[2]);
            if ($data['commentid']) {
                $data['listener'] = $matchs[1];
            }
        }
        if (!$message) {
            return false;
        }
        $data['message'] = $message;
        return true;
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows, $fields) {
        $columns = [];
        while (list($key, $vls) = each($fields)) {
            if (is_string($key)) {
                $columns[] = $key;
            } elseif (is_numeric($key) && is_string($vls)) {
                $columns[] = $vls;
            } else {
                throw new Exception('错误');
            }
        }
        $temp = [];
        foreach ($rows as $row) {
            if (!$migration->filterData($row)) {
                continue;
            }
            $_trow = $migration->transfer($row, $fields);
            if ($_trow) {
                $temp[] = $_trow;
            }
        }
        if (!empty($temp)) {
            $migration->db->createCommand()->batchInsert($migration->tableName, $columns, $temp)->execute();
        }
    }

    /**
     * @inheritdoc
     */
    public function getTableOptions() {
        return [
            'source' => 'sns_group_thread_post',
            'table' => 'sns_dynamic_comment',
            'columns' => [
                'id' => 'pid',
                'user_id' => 'uid',
                'dynamic_id' => 'tid',
                'comment_id' => 'replayid',
                'reply_id' => 'commentid',
                'post' => 'message',
                'author' => function($data) {
                    if (!$data['replayid']) {
                        return '';
                    }
                    return strlen($data['uname']) > 32 ? '' : $data['uname'];
                },
                'listener',
                'status' => function($data) {
                    if ($data['status'] > 0) {
                        return 10;
                    }
                    return $data['status'];
                },
                'created_at' => 'inputtime',
                'updated_at' => function($data) {
                    if ($data['inputtime']) {
                        return $data['inputtime'];
                    }
                    return 0;
                },
                'deleted_at' => function($data) {
                    if ($data['status'] < 0) {
                        return $data['inputtime'];
                    }
                    return 0;
                },
            ],
        ];
    }

}
